<template>
    <div>
        <el-dialog title="视频监控" :visible.sync="dialogVisible" v-if="dialogVisible" :before-close="closeAddDialog"
            :modal-append-to-body="false" :close-on-click-modal="false" :modal="true">
            <span slot="title" class="dialog-title">
                <div class="title">视频监控</div>
            </span>
            <div class="div_box">
                <div>
                    <!-- <el-input v-model="orgName" placeholder="请输入组织机构" class="el_input" size="medium" maxlength="10"
                        suffix-icon="el-icon-search" @input="onchange"></el-input> -->
                    <!-- <el-button type="primary" size="mini" style="border-radius: 5px;color:#D4D4D4;margin-left: 8px;"
                    @click="searchClick">查 询</el-button> -->
                    <el-tree ref="vuetree" :data="dataTree" :props="defaultProps" @node-click="handleNodeClick" lazy
                        :load="loadNode" check-strictly node-key="id">
                        <div class="custom-tree-node" slot-scope="{ node, data }">
                            <div v-if="node.level == 1">
                                <div>{{ node.label }}</div>
                                <div style="margin-top: 5px">设备总数：{{ data.sum }}</div>
                            </div>
                            <div v-else-if="node.level == 4"
                                style="display: flex; align-items: center; padding-left: 6px">
                                <i class="iconfont jiankong"
                                    style="color: #01def9; margin-right: 5px; font-size: 1.5vw"></i>
                                <div :title="data.mountingPoint">
                                    {{ node.label.slice(-8) }} / {{ data.mountingPoint }}
                                </div>
                            </div>
                            <span v-else>{{ node.label }}</span>
                        </div>
                    </el-tree>
                </div>
                <div>
                    <div class="header">
                        <div class="header_box">
                            <el-button size="mini" type="primary" @click="clickFun()"
                                v-preventReClick="1000">全屏</el-button>
                            <img class="img" :src="spanCell == 24 ? one_active : one" @click="onCell('1')" />
                            <img class="img" :src="spanCell == 12 ? four_active : four" @click="onCell('4')" />
                            <img class="img" :src="spanCell == 8 ? six_active : six" @click="onCell('6')" />
                            <img class="img" :src="spanCell == 6 ? nine_active : nine" @click="onCell('12')" />

                            <!-- <el-button size="mini" type="primary" @click="onStop('56053697')"
                                v-preventReClick="1000">停止</el-button> -->
                            <!-- <el-button size="mini" type="primary" @click="onChange('56054088')"
                                v-preventReClick="1000">56054088</el-button> -->
                        </div>
                    </div>
                    <div class="main" id="camara">
                        <el-row>
                            <el-col :span="spanCell" v-for="(item, index) in list" :key="index"
                                :style="{ height: heightCell }">
                                <div class="camara_box" :id="`camara_box${index}`" @click="videoDetails(index)"
                                    @mouseover="showIcon(index)" @mouseout="hideIcon(index)" :style="choiceIndex == index ? 'border: 1px solid #01DEF9;' : ''
                                        ">
                                    <div>
                                        <!-- <div :id="`265Player2${item.deviceId}`" class="camara_video"></div> -->
                                    </div>
                                    <div class="spaceName">
                                        <div>{{ item.spaceName || "" }}</div>
                                        <div>{{ item.deviceId || "" }}</div>
                                    </div>
                                    <div class="iconfontcha" v-show="item.spaceName" @click="onCha(item, index)">
                                        <i class="iconfont cha"></i>
                                    </div>
                                    <div class="none" v-if="item.deviceId == ''">
                                        暂无视频配置
                                    </div>
                                </div>
                            </el-col>
                        </el-row>
                    </div>
                </div>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import { reqSpaceManager, reqDeviceList } from "@api/api.js";
import { reqOrgCamera } from "@api/apiDatav.js";
import screenfull from "screenfull";
import { mapState } from "vuex";

export default {
    data() {
        return {
            one: require("@assets/images/one-screen.png"),
            four: require("@assets/images/four-screen.png"),
            six: require("@assets/images/six-screen.png"),
            nine: require("@assets/images/twelve-screen.png"),
            one_active: require("@assets/images/one-screen-active.png"),
            four_active: require("@assets/images/four-screen-active.png"),
            six_active: require("@assets/images/six-screen-active.png"),
            nine_active: require("@assets/images/twelve-screen-active.png"),
            dialogVisible: false,
            span: 8,
            camaraNums: 6,
            isFullFlag: false,

            // 摄像头
            player: null, //萤石云
            player2: null, //宏视
            codec: 1,
            isPause: true,
            token: "",

            // 给12个初始化空数据
            list: [
                {
                    spaceName: "",
                    deviceId: "",
                    flag: false,
                    index: 0,
                },
                {
                    spaceName: "",
                    deviceId: "",
                    flag: false,
                    index: 1,
                },
                {
                    spaceName: "",
                    deviceId: "",
                    flag: false,
                    index: 2,
                },
                {
                    spaceName: "",
                    deviceId: "",
                    flag: false,
                    index: 3,
                },
                {
                    spaceName: "",
                    deviceId: "",
                    flag: false,
                    index: 4,
                },
                {
                    spaceName: "",
                    deviceId: "",
                    flag: false,
                    index: 5,
                },
                {
                    spaceName: "",
                    deviceId: "",
                    flag: false,
                    index: 6,
                },
                {
                    spaceName: "",
                    deviceId: "",
                    flag: false,
                    index: 7,
                },
                {
                    spaceName: "",
                    deviceId: "",
                    flag: false,
                    index: 8,
                },
                {
                    spaceName: "",
                    deviceId: "",
                    flag: false,
                    index: 9,
                },
                {
                    spaceName: "",
                    deviceId: "",
                    flag: false,
                    index: 10,
                },
                {
                    spaceName: "",
                    deviceId: "",
                    flag: false,
                    index: 11,
                },
            ],
            t: null,
            i: 0,
            timer: null,

            currentPage: 0,
            totalPage: 0,

            spanCell: 12,
            heightCell: "49.9%",
            choiceIndex: 0,

            // 左侧
            dataTree: [],
            defaultProps: {
                children: "children",
                label: "orgName",
                isLeaf: "hasChildren",
                id: "id",
            },
            orgName: "",
        };
    },
    watch: {},
    computed: {
        ...mapState(["user"]),
    },
    methods: {
        // 鼠标移入
        showIcon(index) {
            // this.list[index].flag = true;
        },
        //   鼠标移出
        hideIcon(index) {
            // this.list[index].flag = false;
        },
        // 删除当前设备
        onCha(e, index) {
            console.log(e);
            this.list.forEach((item) => {
                if (item.deviceId == e.deviceId && item.deviceId != "") {
                    item.deviceId = "";
                    item.spaceName = "";
                    return;
                }
            });
            this.onStop2(index);
        },
        // 获取组织机构列表
        async getOrgList() {
            let params2 = {
                tenantId: this.user.tenantId,
                userId: this.user.userId,
                roleName: this.user.roleName,
            };
            let res2 = await reqOrgCamera(params2);
            if (res2.code !== 20000) return this.$modal.notifyWarning(res2.message);
            this.dataTree = res2.data.rows;
        },
        async loadNode(node, resolve) {
            //   console.log(node);
            if (node.level === 1) {
                // 建筑物
                let data = [];
                let params = {
                    userId: this.user.userId,
                    roleName: this.user.roleName,
                    metaCode: 1,
                    orgId: node.data.orgId, //组织机构id
                    isStatistics: 0,
                };
                let res = await reqSpaceManager(1, 999, params);
                res.data.rows.forEach((item) => {
                    data.push({
                        orgName: item.name,
                        id: item.id,
                        orgId: node.data.orgId, //组织机构id
                        parentId: item.id, //建筑物id
                        hasChildren: false, //无子级
                    });
                });
                return resolve(data);
            } else if (node.level === 2) {
                // 楼层
                let data = [];
                let params = {
                    userId: this.user.userId,
                    roleName: this.user.roleName,
                    metaCode: 2,
                    parentId: node.data.id, //建筑物id
                    orgId: node.data.orgId, //组织机构id
                    isStatistics: 0,
                };
                let res = await reqSpaceManager(1, 999, params);
                res.data.rows.forEach((item) => {
                    data.push({
                        orgName: item.name,
                        orgId: node.data.orgId, //组织机构id
                        parentId: node.data.id, //建筑物id
                        floorId: item.id, //楼层id
                        hasChildren: false, //无子级
                    });
                });
                return resolve(data);
            } else if (node.level === 3) {
                // 设备
                let data = [];
                let params = {
                    userId: this.user.userId,
                    roleName: this.user.roleName,
                    tenantId: this.user.tenantId,
                    buildingId: node.data.parentId, //建筑物id
                    orgId: node.data.orgId, //组织机构id
                    floorId: node.data.floorId, //楼层id
                    // classMark: "V380",
                    productId: "1503927023020938595", //摄像机产品id
                };
                let res = await reqDeviceList(1, 999, params);
                // console.log(res);
                res.data.rows.forEach((item) => {
                    // if(item.protocol=='4'){
                    //     // 萤石云设备 设备id为空 从imei取值
                    //     item.deviceId=item.imei.slice(-4)//截取后四位
                    // }
                    data.push({
                        orgName: item.imei,
                        id: item.id,
                        deviceId: item.deviceId,
                        spaceName: item.spaceName,
                        mountingPoint: item.mountingPoint,
                        classMark: item.classMark,
                        protocol: item.protocol,
                        imei: item.imei,
                        sn: item.sn,
                        hasChildren: true, //无子级
                    });
                });
                return resolve(data);
            } else {
                return resolve([]);
            }
        },
        // 点击一条
        async handleNodeClick(data, checked) {
            console.log(data);
            // console.log(this.list);
            if (checked.level == 4) {
                let judge = false;
                this.list.forEach((item) => {
                    if (
                        (item.deviceId == data.imei.slice(-8) &&
                            item.index == this.choiceIndex &&
                            data.protocol == "4") ||
                        (item.deviceId == data.deviceId &&
                            item.index == this.choiceIndex &&
                            data.classMark == "V380")
                    ) {
                        judge = true;
                    }
                });
                if (judge) return; //设备已播放不执行下面
                // 选中设备
                this.list.forEach(async (item) => {
                    // 宏视
                    if (item.deviceId == data.deviceId && data.classMark == "V380") {
                        // this.onStop(item.deviceId)
                        await this.onStop2(item.index);
                        item.deviceId = "";
                        item.spaceName = "";
                    } else if (
                        item.deviceId == data.imei.slice(-8) &&
                        data.protocol == "4"
                    ) {
                        // 萤石云
                        await this.onStop2(item.index);
                        item.deviceId = "";
                        item.spaceName = "";
                    }
                });
                // 播放设备
                this.list[this.choiceIndex].spaceName = data.spaceName;
                if (data.protocol == "4") {
                    var element = document.getElementById(
                        `camara_box${this.choiceIndex}`
                    );
                    var element2 = element.firstElementChild; // 获取子元素
                    element2.innerHTML = `<div id="265Player2${data.imei.slice(
                        -8
                    )}" class="camara_video"></div>`; // 给dom元素赋值id
                    // 萤石云
                    this.list[this.choiceIndex].deviceId = data.imei.slice(-8);
                    await this.getaddress(data);
                } else {
                    var element = document.getElementById(
                        `camara_box${this.choiceIndex}`
                    );
                    var element2 = element.firstElementChild; // 获取子元素
                    element2.innerHTML = `<div id="265Player2${data.deviceId}" class="camara_video"></div>`; // 给dom元素赋值id
                    // 宏视
                    this.list[this.choiceIndex].deviceId = data.deviceId;
                    this.playAddress(data.deviceId);
                }
            }
            // console.log(this.list);
        },
        // 删除DOM
        onStop2(index) {
            console.log(index, "index");
            var element = document.getElementById(`camara_box${index}`);
            var element2 = element.firstElementChild; // 获取要删除的元素
            element2.innerHTML = ""; // 这将替换所有子元素

            // -----------------------------
            // 方法一
            // 获取第一个匹配的元素
            // var element = document.getElementById(`camara_box${index}`);

            // var item = { deviceId: '' };
            //  // 创建一个新的div元素
            // var newDiv = document.createElement('div');
            // // 设置新的id和class属性
            // // 注意：我们不能直接使用模板字面量语法在原生JavaScript中，但我们可以拼接字符串
            // var newId = `265Player2${item.deviceId}`;
            // newDiv.id = newId;
            // newDiv.className = 'camara_video';
            // newDiv.style.zIndex='1';
            // newDiv.style.minWidth ='100%';
            // newDiv.style.minHeight ='100%';

            // // 使用replaceChild替换第一个子元素
            // element.replaceChild(newDiv, element.firstElementChild);
        },
        // 删除DOM
        onStop(deviceId) {
            var item = { deviceId: "" };
            var element = document.getElementById(`265Player2${deviceId}`); // 获取要删除的元素
            element.innerHTML = `<div :id="'265Player2${item.deviceId}''" class="camara_video"></div>`; // 这将替换所有子元素
            // 删除元素
            // element.remove();
            // // 获取要删除的元素
            // var element = document.getElementById(`265Player2${deviceId}`);
            // // 获取父元素
            // var parent = element.parentNode;
            // // 删除元素
            // parent.removeChild(element);
        },
        videoDetails(index) {
            // console.log(choiceIndex);
            this.choiceIndex = index;
        },

        // 摄像头
        init() {
            this.t = new Api();
            this.t
                .login("yuanliu@hongshi.com", "yuanliuhongshi")
                .then((res) => {
                    console.log(res);
                    if (res.result == 0) {
                        this.token = res.token;
                        // 获取设备列表
                        this.t
                            .getDeviceList(res.token)
                            .then((res) => {
                                if (res.result == 0) {
                                    this.server_ip = res.server_ip;
                                    // this.playAddress(this.i);
                                }
                            })
                            .catch((err) => {
                                console.log(err);
                            });
                    }
                })
                .catch((err) => {
                    console.log(err);
                });
        },
        async playAddress(deviceId) {
            console.log(deviceId, "deviceId");
            let _this = this;
            this.t
                .requestPlayAddress(this.token, deviceId, this.server_ip, 0)
                .then((res) => {
                    if (res.code === 1000) {
                        _this.codec = res.codec;
                        _this.play_token = res.play_token;
                        let width = res.width;
                        let height = res.height;
                        this.player2 = this.t.init(
                            _this.codec,
                            _this.server_ip,
                            _this.play_token,
                            width,
                            height
                        );
                        this.player2.play(`265Player2${deviceId}`, true); //播放事件
                    }
                })
                .catch((err) => {
                    console.log(err);
                });
        },
        // 全屏
        clickFun() {
            this.isFullFlag = !this.isFullFlag;
            const element = document.getElementById("camara"); //指定全屏区域元素
            if (this.isFullFlag) {
                // screenfull.request(element);
                element.requestFullscreen();
            } else {
                document.exitFullscreen();
            }
        },
        // 关闭
        closeAddDialog() {
            this.dialogVisible = false;
            this.choiceIndex = 0;
            this.spanCell = 12;
            this.heightCell = "49.9%";
            this.list.forEach((item) => {
                // this.onStop(item.deviceId)
                item.deviceId = "";
                item.spaceName = "";
                // this.onStop2(item.index)
            });
            // 宏视销毁
            this.t
                .loginOut(this.token)
                .then((res) => {
                    console.log(res);
                })
                .catch((err) => {
                    console.log(err);
                });
            this.destroy();
        },
        onCell(e) {
            if (e == 1) {
                this.spanCell = 24;
                this.heightCell = "100%";
            } else if (e == 4) {
                this.spanCell = 12;
                this.heightCell = "49.9%";
            } else if (e == 6) {
                this.spanCell = 8;
                this.heightCell = "49.9%";
            } else if (e == 12) {
                this.spanCell = 6;
                this.heightCell = "33.33%";
            }
        },

        // 萤石云
        // 获取token
        gettoken() {
            fetch(
                `https://open.ys7.com/api/lapp/token/get?appKey=d6a1a4287b9a4d78adebaa7bbc8c7125&appSecret=6b9102e6b4ef80beb7067be13d08bd2c`,
                {
                    method: "POST",
                }
            )
                .then((response) => response.json())
                .then((res) => {
                    // console.log(res);
                    this.accessToken = res.data.accessToken;
                });
        },
        // 获取播放地址接口
        getaddress(data) {
            // console.log(data.imei.slice(-8));
            fetch(
                `https://open.ys7.com/api/lapp/v2/live/address/get?accessToken=${this.accessToken}&deviceSerial=${data.sn}&supportH265=1&quality=2`,
                {
                    method: "POST",
                }
            )
                .then((response) => response.json())
                .then((res) => {
                    // console.log(res, "data.imei");
                    if (res.code != 200) return this.$modal.notifyWarning(res.msg);
                    let player = new EZUIKit.EZUIKitPlayer({
                        id: `265Player2${data.imei.slice(-8)}`, // 视频容器ID
                        accessToken: this.accessToken,
                        url: res.data.url,
                        useHardDev: true, //开启高性能模式
                        // simple - 极简版; pcLive-pc直播；pcRec-pc回放；mobileLive-移动端直播；mobileRec-移动端回放;security - 安防版;voice-语音版;
                        // template: 'security',
                        plugin: ["talk"], // 加载插件，talk-对讲
                        // width: '100%',
                        // height: '100%',
                    });
                    if (player) {
                        this.stopPromiseshow = false;
                    }
                    this.player = player;
                });
        },
        // 销毁
        destroy() {
            // if (!this.player) return
            this.player.stop();
            this.player.destroy();
            this.player = null;
        },
    },
    mounted() {
        // 监听页面全屏
        window.addEventListener("fullscreenchange", (e) => {
            // console.log(screenfull.isFullscreen);
            this.isFullFlag = screenfull.isFullscreen;
        });
    },
};
</script>

<style scoped lang="less">
.div_box {
    display: flex;

    >div:first-of-type {
        width: 22%;
        padding-right: 15px;
        box-sizing: border-box;
        overflow: hidden;
        /* 隐藏超出部分 */
        text-overflow: ellipsis;
        /* 超出部分显示省略号 */
        white-space: nowrap;
        /* 防止文字换行 */
    }

    >div:last-of-type {
        flex: 1;
    }
}

::v-deep .el-tree {
    height: 73.5vh !important;
    overflow-y: auto !important;
    opacity: 1 !important;
    padding-bottom: 3px;
    padding-right: 5px;
    box-sizing: border-box;
}

::v-deep .el-tree-node__content {
    border-bottom: 1px solid transparent;
    padding-top: 13px !important;
    padding-bottom: 13px !important;
    border-image: linear-gradient(225deg,
            rgba(0, 255, 255, 0),
            #1acafa,
            rgba(0, 255, 255, 0)) 1 1;
}

// el-tree背景色
::v-deep .el-tree-node__content:hover {
    background-color: transparent !important;
}

::v-deep .el-tree-node.is-current>.el-tree-node__content {
    background-color: #4b5f7e66 !important;
}

::v-deep .el-tree-node:focus>.el-tree-node__content {
    background-color: #4b5f7e66 !important;
}

.header {
    width: 100%;
    display: flex;
    justify-content: right;

    .header_box {
        display: flex;
        align-items: center;

        .img {
            width: 24px;
            height: 24px;
            margin-left: 10px;
            cursor: pointer;
        }
    }
}

.main {
    border: 1px solid #cfd3ec38;
    width: 100%;
    margin-top: 10px;
    height: 70vh;

    display: flex;

    .camara_box {
        height: 100%;
        background: black;
        position: relative;
        width: 100%;
        border: 1px solid #cccccc73;
        box-sizing: border-box;
        cursor: pointer;

        // 萤石云宽度撑满设置
        >div:first-of-type {
            width: 100%;
            height: 100%;

            ::v-deep>div:first-of-type {
                width: 100% !important;
                height: 100% !important;
            }

            /* 注意：你不能在::v-deep内部再嵌套::v-deep，但你可以继续选择更深层次的元素 */
            ::v-deep>div:first-of-type>div:first-of-type {
                width: 100% !important;
                height: 100% !important;
                position: relative !important;
            }

            ::v-deep>div:first-of-type>div:first-of-type div {
                width: 100% !important;
                height: 100% !important;
                display: flex;
                justify-content: center;
                align-items: center;
                position: absolute;
            }

            ::v-deep>div:first-of-type>div:first-of-type .loading {
                position: absolute;
                bottom: 9%;
            }

            ::v-deep canvas {
                width: 100% !important;
                height: 100% !important;
            }
        }

        // 萤石云
        .camara_video {
            z-index: 1;
            min-width: 100%;
            min-height: 100%;
            width: 100%;
            height: 100%;
        }

        .spaceName {
            color: #e9e9e9;
            position: absolute;
            top: 4%;
            left: 4%;
            z-index: 2;
        }

        .iconfontcha {
            color: #ffffff;
            position: absolute;
            top: 15px;
            right: 20px;
            z-index: 9999;
            cursor: pointer;
        }

        .deviceId {
            color: #e9e9e9;
            position: absolute;
            top: 9%;
            left: 4%;
            z-index: 2;
        }

        .none {
            color: #cfd3ec38;
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            z-index: 2;
        }
    }

    .el-row {
        width: 100%;
        display: flex;
        flex-wrap: wrap;
        align-items: stretch;
        overflow-y: clip;
    }
}

.title {
    color: #4eaef2 !important;
    font-size: 18px;
    font-weight: 600;
    display: flex;
    align-items: center;
    margin-left: 6px;
}

.dialog-title {
    display: flex;
    justify-content: center;
    width: 100%;
}

::v-deep .el-dialog__body {
    background: none !important;
    min-height: 76vh;
    overflow-y: auto;
    padding: 20px !important;
    color: #f1f1f1;
}

::v-deep .el-dialog {
    width: 90%;
    overflow-y: auto;
    min-height: 76vh;
}

::v-deep .el-dialog__header {
    background: #09143f !important;
    border-bottom: 1px solid #06b1e76e;
    padding: 18px !important;
}

::v-deep .el-dialog__body {
    background: #09143f !important;
}

.el_input {
    width: 100%;
    border-radius: 5px !important;
    border: 1px solid #01def9;
    margin-bottom: 1.5vh;

    ::v-deep .el-input__inner {
        background: #003c9b !important;
        border: none !important;
        border-radius: 5px !important;
    }
}

::v-deep .el-tree-node__expand-icon.is-leaf {
    display: none;
}
</style>
